'''
Created on Feb 14, 2014

@author: yfrank
'''

from threading import Thread as Thread

import socket

from select import select

import time

import Project.Simulation.CodingUtils.Logging as Logging


class ConnectionsThread(Thread):
    '''
    classdocs
    '''
    timeout = 0.1
    sleep_interval = 0.01

    def __init__(self, server):
        super(ConnectionsThread,self).__init__()
        self.server = server
        self.stopped = True


    def init(self):
        self.stopped = False
        host = self.server.host
        port = self.server.port

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            msg = "Binding addr "+str(host)+":"+str(port)
            Logging.log(msg)
            self.server_socket.bind((host, port))
            self.server_socket.listen(0)
            return True
        except Exception:
            Logging.log("Address already in use or inaccessible...")
            return False


    def run(self):

        while (not self.is_stopped()):
            self.handle_acceptable()
            time.sleep(ConnectionsThread.sleep_interval)

    def handle_acceptable(self):

        read_list = [self.server_socket]
        readable, writable, errored = select(read_list, [], [],0)
        for s in readable:
            if s is self.server_socket:
                client_socket, address = self.server_socket.accept()
                read_list.append(client_socket)
                self.server.accept_peer(client_socket,address)


    def stop(self):
        self.stopped = True

    def is_stopped(self):
        return self.stopped


